import React, { useState, useEffect } from 'react';
import { Container, ListGroup, Modal, Button } from 'react-bootstrap';
import axios from 'axios';
import './App.css';
const apiUrl = process.env.REACT_APP_NEWS_URL;
console.log("apiUrl:"+apiUrl);
const ListComponent = () => {
  const [items, setItems] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.post(apiUrl, {
          method: 'get_news_list'
        });
        setItems(response.data);
      } catch (error) {
        console.error('Error fetching data: ', error);
      }
    };

    fetchData();
  }, []);

  const handleShow = async (id) => {
    try {
      const response = await axios.post(apiUrl, {
        method: 'get_news_by_id',
        id: id
      });
      setSelectedItem(response.data);
      setShowModal(true);
    } catch (error) {
      console.error('Error fetching news by id: ', error);
    }
  };

  const handleClose = () => setShowModal(false);

  const renderBodyParagraphs = () => {
    if (!selectedItem || !selectedItem.body) return null;
    const paragraphs = selectedItem.body.split('\\n');
    if (paragraphs.length < 2) return null;
    return paragraphs.slice(1).map((paragraph, index) => (
      <p key={index} className="indent" style={{ margin: '0' }}>
        {`　${paragraph.trim()}`}
      </p>
    ));
  };

  return (
    <>
      <Container>
        <ListGroup>
          {items.map((item, index) => (
            <ListGroup.Item
              key={item.id}
              className="d-flex justify-content-between align-items-center position-relative"
              onClick={() => handleShow(item.id)}
            >
              <div className="d-flex align-items-center">
                <img
                  src={item.image_path}
                  alt="Thumbnail"
                  className="thumbnail"
                />
                <div className="pl-3 content-wrapper">
                  <strong>{item.title}</strong>
                  <br />
                  <sub>{item.source}</sub>
                  <p>{item.summary}</p>
                </div>
              </div>
              <span className="timestamp">
                {new Date(item.publish_date).toLocaleString()}
              </span>
            </ListGroup.Item>
          ))}
        </ListGroup>
      </Container>
      <Modal
        show={showModal}
        onHide={handleClose}
        size="lg"
        centered
        dialogClassName="modal-fullscreen"
      >
        <Modal.Header closeButton>
          <Modal.Title>{selectedItem?.title}</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <p className="indent">{selectedItem?.summary}</p>
          <img
            src={selectedItem?.image_path}
            alt="News Image"
            className="news-image"
          />
          {renderBodyParagraphs()}
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleClose}>
            关闭
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
};

export default ListComponent;